AddCSLuaFile( "client/editor.lua" )

require( "mysql" )
require( "datastream" )

DBInfo = {}
DBTable = {}

function InitTest()
	
	print( "DB FILE INITIATED" )

end
hook.Add( "Initialize", "InitTest", InitTest )

function DatabaseConnect( ply, command, args )
	local Host = args[1]
	local User = args[2]
	local Pass = args[3]
	local DB = args[4]
	local Port = tonumber(args[5])
	
	local db, err = mysql.connect( Host, User, Pass, DB, Port )
	if db == 0 then
		ply:PrintMessage( HUD_PRINTTALK, err )
	else
		ply:PrintMessage( HUD_PRINTTALK, "Connection to " .. DB .. " successful!" )
		DBTable.DB = db
		local PTABLE = mysql.query( db, "SHOW TABLES" )
		local ConcatPTABLE = {}
		for k,v in pairs( PTABLE ) do
			table.insert( ConcatPTABLE, v[1] )
		end
		PrintTable( ConcatPTABLE )
		
		local rp = RecipientFilter()
		rp:AddPlayer( ply )
		
		umsg.Start( "DBCONNECT", rp )
			umsg.String( DB )
			umsg.String( table.concat( ConcatPTABLE, "," ) )
		umsg.End()
	end
end

function DatabaseDisconnect( ply, command, args )
	local DB = args[1]
	
	local succ, err = mysql.disconnect( DBTable.DB )
	if !succ then
		ply:PrintMessage( HUD_PRINTTALK, err )
	else
		ply:PrintMessage( HUD_PRINTTALK, "Disconnection from " .. DB .. " successful!" )
		DBTable.DB = nil
		
		local rp = RecipientFilter()
		rp:AddPlayer( ply )
		
		umsg.Start( "DBDISCONNECT", rp )
			umsg.String( DB )
		umsg.End()
	end
end

function DatabaseQuery( ply, command, args )
	local DB = args[1]
	local MYSQL = args[2]
	local OPT = args[3] or ""
	
	local DATA, succ, err = mysql.query( DBTable.DB, MYSQL )
	
	if !succ then
		ply:PrintMessage( HUD_PRINTTALK, err )
	else
		datastream.StreamToClients( { ply }, "QueryStream" .. OPT, { DATA } )	//Work on making sure the player knows to wait for the stream here
	end
	
end

function DatabaseChange( ply, command, args )	//Use this to send manipulating commands to the DB. No need to resend the value back to the client, they already have it temporarily.
	local DB = args[1]
	local MYSQL = args[2]
	
	local DATA, succ, err = mysql.query( DBTable.DB, MYSQL )
	
	if !succ then
		ply:PrintMessage( HUD_PRINTTALK, err )
	end
	
end
concommand.Add( "DatabaseQuery", DatabaseQuery )	//Weirdest reason ever, but the other names for these concommands don't work.
concommand.Add( "DatabaseQuery1", DatabaseConnect )
concommand.Add( "DatabaseQuery2", DatabaseDisconnect )
concommand.Add( "DatabaseQuery3", DatabaseChange )